'use strict';

import { Controller } from 'egg';

class UsersController extends Controller {
    async userList() {
        const {ctx} = this;
        // const id = ctx.params.id;
        const userList = await ctx.service.users.getList()
        ctx.body = {
            error_code: ctx.helper.addOne(0),
            msg: 'get success',
            result: userList
        }
    }

    async userSave() {
        const {ctx} = this;
        const param = ctx.request.body;
        let userData = param.userData;
        let hasSave = false;
        let msg: string='';
        if (userData._id) {
            await ctx.service.users.update(userData).then((res) => {
                console.log(res);
                hasSave = res.result;
                msg = res.resultMsg;
            }).catch((e)=>{
                console.error('更新失败:',e);
                msg='更新失败';
            })
        } else {
            await ctx.service.users.save(userData).then((res) => {
                hasSave = res.result;
                msg = res.resultMsg;
                // if(res){
                //     msg = '保存成功';
                // }else{
                //     msg='保存失败'
                // }
            }).catch(e => {
                console.error('保存失败:',e);
                msg = '保存失败';

            });
        }
        ctx.body = {
            error_code: ctx.helper.addOne(1),
            success: hasSave,
            msg:msg

        }
    }

    async userDelete() {
        const {ctx} = this;
        const param = ctx.request.body;
        const id = param.id;
        let hasDelete = false;
        if (id) {
            await ctx.service.users.delete(id).then((res:any) => {
                hasDelete = res.deletedCount > 0 ? true : false;
            }).catch(e => {
                console.log(e);
            });
        }
        ctx.body = {
            error_code: ctx.helper.addOne(2),
            success: hasDelete
        }
    }


}

module.exports = UsersController;
